<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1200px" @open="open" @close="close">
    <el-form class="tl-form" ref="dealform" :model="model" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="邀请决策" prop="invitedecisionusername">
            <el-input v-model="model.invitedecisionusername" class="tl-ref-selector" disabled>
              <el-button slot="append" type="primary" icon="el-icon-search" @click="openMpmProjectResourcePoolDialog"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
      <el-row>
        <el-col :span="24">
          <el-divider content-position="center"><span>【以下信息为只读信息】</span></el-divider>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-divider content-position="left"><span>【项目】相关信息</span></el-divider>
        </el-col>
      </el-row>
      <el-tabs type="border-card" v-model="tabName">
        <el-tab-pane label="立项信息" name="projectbasicinfo">
          <el-row>
            <el-col :span=" 12">
              <el-form-item label="机会点" prop="chanceclue">
                <el-input v-model="model.chanceclue" :disabled="true" class="tl-ref-selector">
                  <el-button slot="append" type="primary" icon="el-icon-search" @click="openChanceclueDialog" v-if="!disableSave"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目编号" prop="projectcode">
                <el-input v-model="model.projectcode" :disabled="true" placeholder="系统自动生成"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目名称" prop="projectname" :rules="rules.rulesForInfo">
                <el-input v-model="model.projectname" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="可参与金额" prop="participatemoney" :rules="rules.rulesForInfo">
                <el-input-number v-model="model.participatemoney" controls-position="right" :step="1" :min="0" :precision="2" style="width:91%" :disabled="true"></el-input-number><span>万元</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目级别" prop="projectlevel" :rules="rules.rulesForInfo">
                <el-select v-model="model.projectlevel" filterable clearable>
                  <el-option v-for="item in codeModel.projectlevelList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购模式" prop="purchasepattern" :rules="rules.rulesForInfo">
                <el-select v-model="model.purchasepattern" filterable clearable>
                  <el-option v-for="item in codeModel.MpmPurchasePatternList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划开始日期" prop="planstartdate" :rules="rules.rulesForInfo">
                <el-date-picker v-model="model.planstartdate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划结束日期" prop="planenddate" :rules="rules.rulesForInfo">
                <el-date-picker v-model="model.planenddate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="12">
              <el-form-item label="预签日期" prop="bidsigndate" :rules="rules.rulesForInfo">
                <el-date-picker v-model="model.bidsigndate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="创建部门" prop="deptname" :rules="rules.rulesForInfo">
                <tl-ref-dept v-model="model.deptname" :initDisplayData.sync="model.deptname" dataType="code" nameType="fullname" @confirm="onSelectDept" :singleSelect="true" :externalQueryParam="{qry_enabled:1}" :disabled="true">
                </tl-ref-dept>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="项目周期" prop="bidcycle" :rules="rules.rulesForInfo">
                <el-input v-model="model.bidcycle" style="width:93%"></el-input><span>天</span>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="发标日期" prop="bidbegindate" :rules="rules.rulesForInfo">
                <el-date-picker v-model="model.bidbegindate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="截标日期" prop="bidenddate" :rules="rules.rulesForInfo">
                <el-date-picker v-model="model.bidenddate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目经理" prop="projectmanager" :rules="rules.rulesForInfo">
                <el-input v-model="model.projectmanager" :disabled="true"></el-input>
                <!-- <el-input v-model="model.projectmanager" :disabled="true" class="tl-ref-selector">
                  <el-button slot="append" type="primary" icon="el-icon-search" @click="openMpmProjectManagerPoolDialog"
                    v-if="!disableSave"></el-button>
                </el-input> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="Owner" prop="ownercode" :rules="rules.rulesForInfo">
                <tl-ref-user v-model="model.ownercode" :initDisplayData.sync="model.owner" dataType="code" :singleSelect="true" :disabled="disableSave">
                </tl-ref-user>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="项目所属组织" prop="orgname">
                <el-input v-model="model.orgname" :readonly="true" :disabled="true"></el-input>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="Sponsor" prop="sponsorcode" :rules="rules.rulesForInfo">
                <tl-ref-user v-model="model.sponsorcode" :initDisplayData.sync="model.sponsor" dataType="code" :singleSelect="true" :disabled="disableSave">
                </tl-ref-user>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="决策组人员" prop="decisionusername" :rules="rules.rulesForInfo">
                <el-input v-model="model.decisionusername" :disabled="true" class="tl-ref-selector">
                  <el-button slot="append" type="primary" icon="el-icon-search" @click="openMpmProjectResourcePoolDialog" v-if="!disableSave"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="项目背景概述" prop="background">
                <el-input v-model="model.background" type="textarea" :rows="4" maxlength="1000" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item label="项目概述" prop="importance">
                <el-input v-model="model.importance" type="textarea" :rows="4" maxlength="1000" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
          <!-- <el-row>
            <el-col :span="24">
              <el-form-item label="涉及产品范围" prop="productrange">
                <el-input v-model="model.productrange" type="textarea" :rows="4" maxlength="1000" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="项目目标" prop="target">
                <el-input v-model="model.target" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="总体策划" prop="summary">
                <el-input v-model="model.summary" type="textarea" :rows="4" maxlength="1000" show-word-limit></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-collapse>
            <el-collapse-item title="【单据】申请信息">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人姓名" prop="username" :rules="rules.rulesForInfo">
                    <el-input v-model="model.username" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人工号" prop="usercode">
                    <el-input v-model="model.usercode" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="申请人部门" prop="applydeptname">
                    <el-input v-model="model.applydeptname" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="申请人公司" prop="applyorgname">
                    <el-input v-model="model.applyorgname" :disabled="true"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>
          </el-collapse>
          <el-collapse value="approval">
            <el-collapse-item title="【单据】审批历史" name="approval">
              <div>
                <el-table v-show="listMode" class="tl-table" ref="mainTable" v-loading="loading" :data="datas" height="240px" @sort-change="doSortChange" row-key="id" border fit>
                  <el-table-column type="index" label="序号" width="55px" align="center"> </el-table-column>
                  <el-table-column prop="dispnodeid" label="流程节点" :show-overflow-tooltip="true" width="150px">
                  </el-table-column>
                  <el-table-column prop="dispapprovaluserid" label="审批人" width="150px" align="center">
                  </el-table-column>
                  <el-table-column prop="dispstate" label="状态" width="150px" align="center">
                  </el-table-column>
                  <el-table-column prop="approvaldate" label="审批时间" width="160px" sortable="custom" sort-by="approvaldate" align="center"></el-table-column>
                  <el-table-column prop="approvalopinion" label="审批意见" :show-overflow-tooltip="true" width="300px">
                  </el-table-column>
                </el-table>
                <!-- 列表分页 -->
                <el-row v-show="listMode" class="pagebar" ref="pager">
                  <el-pagination @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination">
                  </el-pagination>
                </el-row>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
        <el-tab-pane label="客户信息" name="projectcustomerinfo">
          <div style="margin-top:1px;margin-left:-20px" class="mancomment">
            <el-row>
              <el-col :span=" 12">
                <el-form-item label="客户名称" prop="clientname" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientname" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户部门" prop="clientdept" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientdept" :disabled="true"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span=" 12">
                <el-form-item label="客户决策链支持度" prop="clientsupport" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientsupport"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="客户需求分析" prop="clientdemand" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.clientdemand" type="textarea" :rows="6" maxlength="1000" show-word-limit>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="客户决策模式" prop="decisionmode" :rules="rules.rulesForCustomeryInfo">
                  <el-input v-model="model.decisionmode" type="textarea" :rows="6" maxlength="1000" show-word-limit>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="竞争对手" name="projectcompetitorinfo">
          <div style="margin-top:1px;margin-left:-50px" class="mancomment">
            <el-row>
              <el-col :span="24">
                <el-form-item label="主要竞争对手" prop="competitor" :rules="rules.rulesForCompetitorInfo">
                  <el-input v-model="model.competitor" type="textarea" :rows="8" maxlength="1000" show-word-limit>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="SWOT分析" prop="swot" :rules="rules.rulesForCompetitorInfo">
                  <el-input v-model="model.swot" type="textarea" :rows="8" maxlength="1000" show-word-limit></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <tl-approval-history ref="history" sourceType="MpmProject" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit">取消</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave">
        <svg-icon icon-class="save" />保存
      </el-button>
      <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval">
        <svg-icon icon-class="send" />提交审批
      </el-button>
      <tl-attachment sourceType="MpmProject" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit">
      </tl-attachment>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory">
        <svg-icon icon-class="list" />审批历史
      </el-button>
      <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableEditSubmit" :disabled="disableDelApproval">
        <svg-icon icon-class="undo" />取消审批
      </el-button>
    </div>
    <tlmpmProject-manager-pool-ref ref="mpmProjectManagerPoolRef" @confirm="getMpmProjectManagerData" :isSingleSelect="true" :externalQueryParam="externalMQueryParamForPool">
    </tlmpmProject-manager-pool-ref>
    <tlmpmProject-resource-pool-ref ref="mpmProjectResourcePoolRef" @confirm="getMpmProjectResourceData" :isSingleSelect="false" :externalQueryParam="externalDQueryParamForPool">
    </tlmpmProject-resource-pool-ref>
    <tlchange-ref ref="changeRef" @confirm="getChanceclueData" :isSingleSelect="true" :fieldKey="rowKeyStr">
    </tlchange-ref>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
import { mixin_page_fields_custom } from '@misui/mixins/mixin_page_fields_custom'
/** 子组件 */
import { validateNull } from '@tapui/utils/validate'
import tlmpmProjectManagerPoolRef from '@/views/mpm/mpmProjectManagerPool/refList'
import tlmpmProjectResourcePoolRef from '@/views/mpm/mpmProjectResourcePool/refList'
import tlchangeRef from '@/views/mpm/mpmProject/refListChange'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit, mixin_page_fields_custom],
  components: { tlmpmProjectManagerPoolRef, tlmpmProjectResourcePoolRef, tlchangeRef },
  data() {
    var validateForTab = (rule, value, callback) => {
      if (!value) {
        this.tabName = rule.tabname
        return callback(new Error('请输入内容'))
      } else {
        return callback()
      }
    }
    return {
      moduleTitle: '项目立项',
      urlPrefix: '/mpm/projectpolymerization/',
      url: {
        // 额外的url
        queryOrgByDeptId: '/mpm/project/queryOrgByDeptId',
        list: '/cbo/approvalNodeIns/list'
      },
      tabName: 'projectbasicinfo',
      sorterInfo: {
        // 排序参数
        sidx: 'id',
        sord: 'desc'
      },
      datas: [],
      initCbousers: [], // 页面初始化项目组成员
      pageInfo: {
        // 分页参数
        currentPage: 1, // 当前页面
        pageSize: 10, // 每页记录数
        pageSizes: ['10', '50', '100'],
        totalCount: 0 // 总数
      },
      rowKeyStr: 'CODE',
      loading: false,
      visible: false,
      listMode: true,
      externalMQueryParamForPool: {},
      externalDQueryParamForPool: {},
      // 项目立项规则校验重写
      addRules: {
        // 基本信息TAB表单校验
        rulesForInfo: [
          { validator: validateForTab, tabname: 'projectbasicinfo', trigger: 'change' },
          { required: 'true', message: '请输入内容', trigger: 'change' }
        ],
        // 案例概述TAB表单验证
        rulesForCustomeryInfo: [
          { validator: validateForTab, tabname: 'projectcustomerinfo', trigger: 'change' },
          { required: 'true', message: '请输入内容', trigger: 'change' }
        ],
        rulesForCompetitorInfo: [
          { validator: validateForTab, tabname: 'projectcompetitorinfo', trigger: 'change' },
          { required: 'true', message: '请输入内容', trigger: 'change' }
        ]
      }
    }
  },
  props: {
  },
  methods: {
    assignDefaultValue() {
      if (this.isAdd) {
        this.$set(this.model, 'applyorgcode', this.org.code)
        this.$set(this.model, 'applyorgname', this.org.name)
        this.$set(this.model, 'orgcode', this.org.code)
        this.$set(this.model, 'applydeptcode', this.dept.code)
        this.$set(this.model, 'deptcode', this.dept.code)
        this.$set(this.model, 'applydeptname', this.dept.fullname)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        // this.$set(this.model, 'projectmanagercode', this.user.code)
        // this.$set(this.model, 'projectmanager', this.user.name)
        this.$set(this.model, 'docdate', new Date())
        this.$set(this.model, 'applydate', new Date())
        this.$set(this.model, 'projecttype', '0')
      }
    },
    // loaded() {
    //   页面加载完毕执行
    //     if (!this.isAdd && this.model.docno) {
    //       this.title = this.title + `（单据编号：${this.model.docno}）`
    //     }
    // },
    beforeApproval() {
      if (
        this.model.projectmanagercode === this.model.sponsorcode ||
        this.model.projectmanagercode === this.model.ownercode ||
        this.model.sponsorcode === this.model.ownercode
      ) {
        this.$tap.alert('项目经理、sponsor和owner不能重复，请确认！', 'warning')
        return false
      } else {
        return true
      }
    },
    /** 提交审批 */
    doSubmitApproval() {
      if (!this.url.submit) {
        this.$tap.alert('请设置审批地址!', 'warning')
        return
      }
      let fileValidate = true
      this.$refs.form.validate(valid => {
        if (!valid) {
          fileValidate = false
        }
      })
      if (!fileValidate) {
        return
      }
      if (!this.beforeApproval()) {
        return
      }
      this.submitLoading = true
      this.$tap
        .confirm('确定提交审批吗？提交后，单据内容不可修改！')
        .then(_ => {
          this.$set(this.model, 'projectstate', '0')
          if (this.isAdd) {
            this.doAdd()
          } else {
            this.doEdit()
          }
          putAction(this.url.submit, this.model).then(res => {
            if (res.success) {
              this.$tap.message(res.message, 'success')
              this.queryData(this.model.id)
              this.afterApproval()
            } else {
              this.$tap.alert(res.message, 'warning')
            }
            this.submitLoading = false
          })
        })
        .catch(_ => {
          this.submitLoading = false
        })
    },
    /** 执行编辑提交 */
    doEdit() {
      this.saveLoading = true
      putAction(this.url.edit, this.model)
        .then(res => {
          if (res.success) {
            this.$emit('refresh')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch(err => {
          this.saveLoading = false
        })
    },
    // 选择项目所属部门
    onSelectDept(selectedDepts) {
      const selectedDept = selectedDepts[0]
      const { id, code, fullname } = selectedDept
      this.$set(this.model, 'deptcode', code)
      this.$set(this.model, 'deptname', fullname)
      const param = {
        deptId: id
      }
      getAction(this.url.queryOrgByDeptId, param).then(res => {
        if (res.success) {
          const { code: orgcode, name: orgname } = res.result
          this.$set(this.model, 'orgcode', orgcode)
          this.$set(this.model, 'orgname', orgname)
        } else {
          this.$tap.alert('已选部门关联公司信息错误，请联系系统管理员')
        }
      })
    },
    open() {
      this.model = {}
      this.$nextTick(() => {
        this.getFieldsCustomSetting('projectpolymerization')
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then(_ => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then(_ => {
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then(_ => {
            this.loaded()
          })
        }
      })
      this.datas = []
      this.loadData({ currentPage: 1 })
    },
    /** 加载审批历史列表数据 */
    loadData(paramMap) {
      if (validateNull(paramMap) === false && Object.keys(paramMap).indexOf('currentPage') > -1) {
        this.pageInfo.currentPage = paramMap['currentPage']
      }
      // 查询条件
      var params = this.getQueryParams()
      // 数据查询
      this.loading = true
      getAction(this.url.list, params)
        .then(res => {
          if (res.success) {
            this.datas = res.result.dataList
            this.pageInfo.totalCount = res.result.totalCount
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.loading = false
        })
        .catch(err => {
          this.loading = false
        })
    },
    /** 执行查询 */
    doQuery() {
      this.loadData({ currentPage: 1 })
    },
    /** 获取查询参数 */
    getQueryParams() {
      let param = {
        qry_sourcetype: 'MpmProject',
        qry_sourceid: 0
      }
      if (!this.isAdd) {
        param.qry_sourceid = this.id
      }
      Object.assign(param, this.sorterInfo)
      param.currentPage = this.pageInfo.currentPage
      param.pageSize = this.pageInfo.pageSize
      return param
    },
    /** 表格列排序 */
    doSortChange(columnInfo, prop, order) {
      if (columnInfo.column === null) {
        return
      }
      // 不排序
      if (validateNull(columnInfo.order)) {
        this.loadData({})
        return
      }
      // 升序或者降序排序
      if (columnInfo.column.sortBy) {
        this.sorterInfo.sidx = columnInfo.column.sortBy
      } else {
        this.sorterInfo.sidx = columnInfo.prop
      }
      this.sorterInfo.sord = columnInfo.order.replace('ending', '')
      this.loadData({})
    },
    /** 每页大小改变 */
    doChangeSize(val) {
      if (this.pageInfo.pageSize !== val) {
        this.pageInfo.pageSize = val
        this.pageInfo.currentPage = 1
        this.loadData({})
      }
    },
    /** 页面跳转 */
    doChangeIndex(val) {
      if (this.pageInfo.currentPage !== val) {
        this.pageInfo.currentPage = val
        this.loadData({})
      }
    },
    drawDiagram(map) {
      /* eslint-disable*/
      $('#history-myflow').html('')
      let restore = map.strdiagram
      restore = restore.replace(/'/g, '"')
      if (restore !== '') {
        restore = JSON.parse(restore)
      }
      let history = map.strhistory
      history = history.replace(/'/g, '"')
      history = history.replace(/activeRects/g, '"activeRects"')
      history = history.replace(/historyRects/g, '"historyRects"')
      history = history.replace(/rects/g, '"rects"')
      history = history.replace(/paths/g, '"paths"')
      history = history.replace(/code/g, '"code"')
      if (history !== '') {
        history = JSON.parse(history)
      }
      $('#history-myflow').myflow(
        $.extend(false, {
          basePath: '',
          restore: restore,
          editable: false,
          ...history
        })
      )
    },
    // 项目级别变更后，清空项目经理和决策组--2-7todo 暂时取消
    clear() {
      if (this.model.projectmanagercode || this.model.decisionusercode) {
        this.$set(this.model, 'projectmanagercode', '')
        this.$set(this.model, 'projectmanager', '')
        this.$set(this.model, 'decisionusercode', '')
        this.$set(this.model, 'decisionusername', '')
      }
    },
    /** 打开项目经理参照 */
    openMpmProjectManagerPoolDialog() {
      const { projectlevel, projecttype } = this.model
      if (!projectlevel) {
        this.$tap.alert('请先选择项目级别！', 'warning')
        this.$refs.mpmProjectManagerPoolRef.visible = false
      } else {
        this.externalMQueryParamForPool = {
          projectlevel: projectlevel,
          projecttype: projecttype
        }
        this.$refs.mpmProjectManagerPoolRef.visible = true
      }
    },
    /** 获取项目经理参照数据 */
    getMpmProjectManagerData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'projectmanagercode', selectionRow.managercode)
      this.$set(this.model, 'projectmanager', selectionRow.managername)
    },
    /** 打开决策组成员参照 */
    openMpmProjectResourcePoolDialog() {
      const { projectlevel, projecttype } = this.model
      if (!projectlevel) {
        this.$tap.alert('请先选择项目级别！', 'warning')
        this.$refs.mpmProjectResourcePoolRef.visible = false
      } else {
        this.externalDQueryParamForPool = {
          projectlevel: projectlevel,
          projecttype: projecttype
        }
        this.$refs.mpmProjectResourcePoolRef.visible = true
      }
    },
    /** 获取决策组成员参照数据 */
    getMpmProjectResourceData(selectionRow, selectKey, selectionValue) {
      if (selectionRow.length > 0) {
        let code = []
        let name = []
        selectionRow.forEach(element => {
          code.push(element.usercode)
          name.push(element.username)
        })
        let codes = ',' + code.join(',') + ','
        let names = name.join(',')
        this.$set(this.model, 'invitedecisionusercode', codes)
        this.$set(this.model, 'invitedecisionusername', names)
      } else {
        let codes = ',' + selectionRow.usercode + ','
        let names = selectionRow.username
        this.$set(this.model, 'invitedecisionusercode', codes)
        this.$set(this.model, 'invitedecisionusername', names)
      }
    },
    /** 打开机会点参照 */
    openChanceclueDialog() {
      this.$refs.changeRef.visible = true
    },
    /** 获取机会点参照数据 */
    getChanceclueData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'chanceclue', selectionRow.CODE)
      this.$set(this.model, 'projectname', selectionRow.PROJECT_NAME)
      this.$set(this.model, 'projectmanager', selectionRow.GARDENER_NAME)
      this.$set(this.model, 'projectmanagercode', selectionRow.GARDENER_CODE)
      this.$set(this.model, 'deptname', selectionRow.CREATOR_DEPT_NAME)
      this.$set(this.model, 'participatemoney', selectionRow.RELEVANT_FUND)
      this.$set(this.model, 'clientname', selectionRow.CLIENT_NAME)
      this.$set(this.model, 'clientdept', selectionRow.CLIENT_DEPT)
    },
    //邀请决策
    doInviteSubmit() {
      this.doSubmitEdit()
      this.$tap.alert('邀请完成', 'success')
    },
    // 保存初始化页面决策组的数据
    loaded() {
      this.initCbousers = this.model.decisionusercode
    },
    saveInviteInfo(resolve, reject) {
      // 校验邀请决策的人员是否重复
      const { decisionusercode, invitedecisionusercode } = this.model
      if (decisionusercode && invitedecisionusercode) {
        var decisionusercodearray = decisionusercode.split(',')
        var invitedecisionusercodearray = invitedecisionusercode.split(',')
        for (let i = 1; i < decisionusercodearray.length - 1; i++) {
          for (let j = 1; j < invitedecisionusercodearray.length - 1; j++) {
            if (decisionusercodearray[i] === invitedecisionusercodearray[j]) {
              this.$tap.alert('邀请决策的人员和原决策组人员重复，请重新选择！', 'warning')
              reject()
            }
          }
        }
        // 把邀请决策的人员添加进原决策组人员
        this.model.decisionusercode = this.model.decisionusercode + this.model.invitedecisionusercode.substring(1)
        this.model.decisionusername = this.model.decisionusername + ',' + this.model.invitedecisionusername
      }
      putAction(this.url.edit, this.model)
        .then(res => {
          if (res.success) {
            this.$emit('refresh')
            resolve()
          } else {
            this.$tap.alert(res.message, 'warning')
            reject()
          }
        })
        .catch(err => {
          this.$tap.alert('添加邀请决策失败，请联系系统管理员', 'warning')
          reject()
        })
    },
    saveApprovalTypeInfo(resolve, reject) {
      const {
        id,
        approvaltype,
        deptcode
      } = this.model
      if (!approvaltype) {
        this.$tap.alert('请选择审批类型')
        reject()
      }
      const param = {
        id,
        approvaltype,
        deptcode
      }
      putAction(this.url.edit, param)
        .then(res => {
          if (res.success) {
            resolve()
          } else {
            this.$tap.alert(res.message, 'warning')
            reject()
          }
        })
        .catch(err => {
          this.$tap.alert('保存审批类型信息失败，请联系系统管理员', 'warning')
          reject()
        })
    }
  }
}
</script>

